# 导入相关库和模块
from fastapi import APIRouter, Depends, Request, Query
from sqlalchemy.orm import Session
from database import SessionLocal
from admin.base_controller import BaseController
from config.logging import logger
from services.admin.user_api_service import UserApiService as AdminUser
from services.admin.user_role_api_service import UserRoleApiService
from services.database_manager import databaseManager
from datetime import datetime
# 定义获取数据库会话的依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# Admin管理员控制器类
class UserApi(BaseController):
    def __init__(self):
        super().__init__()
        self.router = APIRouter()

    async def user_list(self, db: Session = Depends(get_db), email: str = Query(None), name: str = Query(None),
                        page: int = Query(default=1, ge=1), limit: int = Query(default=20, ge=1)):
        """
        管理员列表
        :param email:
        :param db:
        :param name:
        :param page:
        :param limit:
        :return:
        """
        service = AdminUser(db)
        lists = await service.user_list(page, limit, name)
        return self.success_response(data=lists, message="success")

    async def user_detail(self, userId: int, db: Session = Depends(get_db)):
        """
        角色详情
        :param userId:
        :param db:
        :return:
        """
        service = AdminUser(db)
        result = await service.user_detail(userId)
        return self.success_response(data=result, message="success")

    async def user_delete(self, userId: int, db: Session = Depends(get_db)):
        """
        删除管理员
        :param userId:
        :param db:
        :return:
        """
        service = AdminUser(db)
        result = await service.user_delete(userId)
        return self.success_response(data=result, message="success")

    async def user_login(self, userData: dict, db: Session = Depends(get_db)):
        """
        用户登录
        :param userData:
        :param db:
        :return:
        """
        service = AdminUser(db)
        result = await service.user_login(userData)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
            # 正常情况下的返回
        return self.success_response(data=result, message="登录成功")

    async def user_register(self, userData: dict, db: Session = Depends(get_db)):
        """
        注册一个新用户
        :param userData:
        :param db:
        :return:
        """
        service = AdminUser(db)
        result = await service.register_user(userData)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
            # 正常情况下的返回
        return self.success_response(data=result, message="用户添加成功")

    async def user_info(self, request: Request, db: Session = Depends(get_db)):
        """
        用户信息
        :param request:
        :param db:
        :return:
        """
        result = request.state.user
        role_data = UserRoleApiService(db)
        user_role = await role_data.detail_user_role(user_id=result["id"])
        # 提取角色名称和ID
        role_names_ids = [{"role_name": role.name, "role_id": role.id} for role in user_role]

        # 将提取的角色信息添加到用户数据中
        result["role"] = role_names_ids

        return self.success_response(data=databaseManager(db).convert_dict_keys(result), message="success")


# 使用
user_api = UserApi()
router = user_api.router
